package com.swgk.core.view.selection;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.swgk.core.BR;
import com.swgk.core.R;
import com.swgk.core.databinding.XchooseLeftItemBinding;
import com.swgk.core.dialog.BaseBottomDialog;
import com.swgk.core.dialog.DialogViewHolder;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class XChooseDialog extends BaseBottomDialog {

    // 缓存数据集
    private SparseArray<XChooseEntity> mCacheData = new SparseArray<>();
    // 勾选缓存
    private SparseIntArray mCacheFilters = new SparseIntArray();
    // 是否展开数据
    private SparseBooleanArray mCacheExpand = new SparseBooleanArray();
    private SparseArray<String> mNameArrays;

    private ChildAdapter childAdapter;
    private DialogCallBackImpl mCallBack;

    public XChooseDialog(Context context, SparseArray<String> nameArray) {
        super(context, com.swgk.core.R.style.dialog_base, null, Gravity.END);
        mNameArrays = nameArray;
        for (int i = 0; i < mNameArrays.size(); i++) {
            addEntity(mNameArrays.keyAt(i), new ArrayList<>());
        }
    }

    @Override
    protected int dialogLayout() {
        return R.layout.xchoose_left_dialog;
    }

    @Override
    protected void initView(DialogViewHolder holder, Bundle savedInstanceState) {
        TextView resetView = holder.getDialog().findViewById(R.id.reset_view);
        TextView okView = holder.getDialog().findViewById(R.id.ok_view);
        RecyclerView recyclerView = holder.getDialog().findViewById(R.id.type_list);
        childAdapter = new ChildAdapter(context, null, new ItemAction() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemAction(XChooseEntity entity, int childPos) {
                if (mCacheFilters.get(entity.getSort()) == childPos) {
                    return;
                }
                mCacheFilters.put(entity.getSort(), childPos);
                childAdapter.notifyDataSetChanged();
                if (mCallBack != null) {
                    mCallBack.loadChildData(entity, childPos);
                }
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(childAdapter);

        //重置
        resetView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCacheFilters.clear();
                if (mCallBack != null) {
                    mCallBack.reset();
                }
            }
        });

        //确定
        okView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCallBack != null) {
                    mCallBack.result(mCacheData, mCacheFilters);
                }
                dismiss();
            }
        });

        setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mCallBack != null) {
                    mCallBack.onCancel();
                }
            }
        });
    }

    public void addEntity(int index, List<CommonPopEntity> list) {
        addEntity(index, null, list, false);
    }

    public void addEntity(int index, String name, List<CommonPopEntity> list) {
        addEntity(index, name, list, false);
    }

    public void addEntity(int index, List<CommonPopEntity> list, boolean isHide) {
        addEntity(index, null, list, isHide);
    }

    private void addEntity(int index, String name, List<CommonPopEntity> list, boolean isHide) {
        if (!TextUtils.isEmpty(name)) {
            mNameArrays.put(index, name);
        }
        if (mCacheData.get(index) != null) {
            mCacheData.get(index).setHide(isHide);
            if (list == null || list.size() == 0) {
                mCacheData.get(index).setList(new ArrayList<>());
            } else {
                mCacheData.get(index).setList(list);
            }
        } else {
            XChooseEntity chooseEntity = new XChooseEntity(index, mNameArrays.get(index), list);
            chooseEntity.setHide(isHide);
            mCacheData.put(index, chooseEntity);
        }
        mCacheFilters.put(index, 0);
    }

    public void setCallBack(DialogCallBackImpl callBack) {
        mCallBack = callBack;
    }

    /**
     * 显示对话框
     */
    public void showDialog() {
        showDialog(!isShowing());
    }

    public void showDialog(boolean isRef){
        if (mCacheData == null || mCacheData.size() == 0) {
            return;
        }
        List<XChooseEntity> entities = new ArrayList<>();
        for (int i = 0; i < mCacheData.size(); i++) {
            int key = mCacheData.keyAt(i);
            XChooseEntity datum = mCacheData.get(key);
            if (datum.getList() == null || datum.getList().size() == 0) {
                continue;
            }
            entities.add(datum);
        }
        Collections.sort(entities, new Comparator<XChooseEntity>() {
            @Override
            public int compare(XChooseEntity o1, XChooseEntity o2) {
                String o1Sort = String.valueOf(o1.getSort());
                String o2Sort = String.valueOf(o2.getSort());
                return o1Sort.compareTo(o2Sort);
            }
        });
        childAdapter.setDatas(entities);
        if (isRef) {
            show();
        }
    }

    public void initData(SparseArray<XChooseEntity> sparseArray, SparseIntArray map) {
        mCacheFilters = map.clone();
        mCacheData = CopyUtils.deepPopEntityCopy(sparseArray);
    }

    public int getItemPos(int i) {
        return mCacheFilters.get(i);
    }

    public interface DialogCallBackImpl {

        void loadChildData(XChooseEntity entity, int pos);

        void result(SparseArray<XChooseEntity> data, SparseIntArray map);

        void reset();

        void onCancel();
    }

    private class ChildAdapter extends BaseRecycleAdapter<XChooseEntity> {

        ItemAction itemAction;

        public ChildAdapter(Context context, List<XChooseEntity> datas, ItemAction itemAction) {
            super(context, R.layout.xchoose_left_item, datas);
            this.itemAction = itemAction;
        }

        @Override
        public void convert(ItemViewHolder holder, final XChooseEntity entity) {

        }

        @Override
        public int getItemCount() {
            return super.getItemCount();
        }

        @Override
        public void onBindViewHolder(ItemViewHolder holder, int position) {
            super.onBindViewHolder(holder, position);
            XChooseEntity entity = datas.get(position);
            holder.setBinding(BR.viewModel, entity);
            XchooseLeftItemBinding testBinding = (XchooseLeftItemBinding) holder.getmBinding();
            testBinding.tvCategory.setText(entity.getTypeName());

            setVisibility(holder, entity.isHide());

            if (position == datas.size() - 1) {
                testBinding.bottomLine.setVisibility(View.GONE);
            } else {
                testBinding.bottomLine.setVisibility(View.VISIBLE);
            }

            int childPos = mCacheFilters.get(entity.getSort());
            // 选择全部隐藏
            if (childPos == 0) {
                testBinding.tvValue.setVisibility(View.INVISIBLE);
            } else {
                testBinding.tvValue.setText(entity.getItemName(childPos));
                testBinding.tvValue.setVisibility(View.VISIBLE);
            }
            if (entity.getList().size() > 9) {
                testBinding.arrowLayout.setVisibility(View.VISIBLE);
                if (mCacheExpand.get(entity.getSort())) {
                    testBinding.ivArrow.setImageResource(R.drawable.icon_expand_up);
                } else {
                    testBinding.ivArrow.setImageResource(R.drawable.icon_expand_down);
                }
            } else {
                testBinding.arrowLayout.setVisibility(View.GONE);
            }
            testBinding.arrowLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean b = mCacheExpand.get(entity.getSort());
                    if (b) {
                        mCacheExpand.put(entity.getSort(), false);
                    } else {
                        mCacheExpand.put(entity.getSort(), true);
                    }
                    notifyDataSetChanged();
                }
            });
            updateChildRecycler(testBinding.rv, entity, mCacheFilters.get(entity.getSort()), mCacheExpand.get(entity.getSort()));
        }

        public void updateChildRecycler(RecyclerView recyclerView, XChooseEntity parentEntity, int defItem, boolean isExpand) {
            XChooseChildAdapter mAdapter = new XChooseChildAdapter(getContext(),
                    parentEntity.getList(), R.layout.xchoose_left_child_item, isExpand);
            mAdapter.setItemSelect(true);
            if (recyclerView.getItemDecorationCount() > 0) {
                recyclerView.removeItemDecorationAt(0);
            }
            recyclerView.addItemDecoration(new GridItemDecoration(dip2px(10)));
            recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
            recyclerView.setAdapter(mAdapter);
            mAdapter.setDefItem(defItem);
            mAdapter.setOnItemClick(new AdapterOnItemClick<CommonPopEntity>() {
                @Override
                public void onItemClick(CommonPopEntity entity, int position) {
                    if (itemAction != null) {
                        itemAction.onItemAction(parentEntity, position);
                    }
                }
            });
        }

        private void setVisibility(ItemViewHolder holder, boolean isHide) {
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
            if (isHide) {
                holder.itemView.setVisibility(View.GONE);
                layoutParams.height = 0;

            } else {
                holder.itemView.setVisibility(View.VISIBLE);
                layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
            }
            holder.itemView.setLayoutParams(layoutParams);
        }
    }

    public int dip2px(float dipValue) {
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        return (int) (dipValue * dm.density + 0.5f);
    }

    private interface ItemAction {
        void onItemAction(XChooseEntity entity, int childPos);
    }

}
